"""
@Author: CheyenneLam
@Date: 2021-07-02 10:30:00
@LastEditTime: 2021-07-02 10:30:00
@LastEditors: CheyenneLam
@Description: 切分数据文件函数
@FilePath: \Main\process.py
"""

import datetime as dt
import xlwings as xw
from settings import *
import pandas as pd
import numpy as np
import win32com
import win32com.client
from win32com.client import constants as c


def copy_sheet(xlApp, sourceFilePath, targetFilePrefix):
    """
    :param xlApp: excel application
    :param sourceFilePath: 源文件路径
    :param targetFilePrefix: 拆分后文件保存路径
    :return: targetFilePathList：list类型,[目标文件路径,目标文件名,留存sheet名]
    复制拆分excel
    """
    targetFilePathList = []

    # 打开需要拆分的源文件
    logger.debug(f"打开{sourceFilePath}")
    print(f"打开{sourceFilePath}")

    # 查看源文件需要拆分的sheet名
    sheetDict = pd.ExcelFile(sourceFilePath).sheet_names
    keepSheetList = [sheet for sheet in sheetDict]
    print(f'查询有以下sheet：{keepSheetList}')

    # 打开源workbook
    sourceWb = xlApp.Workbooks.Open(sourceFilePath)
    for keepSheetName in keepSheetList:
        targetFileName = f"{targetFilePrefix}_{keepSheetName}"
        targetFilePath = os.path.join(reportPath,f"{targetFileName}.csv")
        # 如果模式为替换或者不存在该拆分后的文件名，就开始拆分文件并另存
        if not(os.path.exists(targetFilePath)) or mode == 1:
            sourceWs = sourceWb.Worksheets(keepSheetName)
            # 新建新的workbook
            targetWb = xlApp.Workbooks.Add()
            # 复制到新workbook
            sourceWs.Copy(targetWb.Worksheets("Sheet1"))
            targetWb.Worksheets("Sheet1").Delete()
            # 另存为
            targetWb.SaveAs(targetFilePath, c.xlCSV)
            targetWb.Close()
            print(f"保存成功{targetFilePrefix}_{keepSheetName}")
            logger.debug(f"保存成功{targetFilePrefix}_{keepSheetName}")
        targetFilePathList.append([targetFilePath,targetFileName,keepSheetName])
    sourceWb.Close()
    return targetFilePathList
